#include "Direct3DFramework.h"

int Direct3DFramework::projCoord(
	DMesh* a_mesh,
	bool*  a_hit,
	float* a_dis,
	V3DF*  a_ori,
	V3DF*  a_dir,
	V2DF   a_pos)
{
	if(a_mesh == 0) return D3D_SUCCESS;
	if(a_hit == 0)  return D3D_SUCCESS;
	if(a_dis == 0)  return D3D_SUCCESS;

	BOOL  hit = 0;
	float dis = 0;
	D3DXMATRIX  iv, iw;
	D3DXVECTOR3 v, ro, rd, rmo, rmd;

	D3DFMesh* mesh = m_meshList[a_mesh->m_meshId];

	//convert screen space to projection view space
	D3DXMatrixInverse(&iv,0,&m_view);

	v.x = (((2.0f*a_pos.x)/m_window->m_windowWidth)-1.0f)/m_proj._11;
	v.y = -(((2.0f*a_pos.y)/m_window->m_windowHeight)-1.0f)/m_proj._22;
	v.z = 1.0f;

	rd.x = v.x*iv._11 + v.y*iv._21 + v.z*iv._31;
	rd.y = v.x*iv._12 + v.y*iv._22 + v.z*iv._32;
	rd.z = v.x*iv._13 + v.y*iv._23 + v.z*iv._33;
	ro.x = iv._41;
	ro.y = iv._42;
	ro.z = iv._43;

	//convert projection to 
	D3DXMatrixInverse(&iw,0,&mesh->m_world[a_mesh->m_meshMat]);

	D3DXVec3TransformCoord(&rmo,&ro,&iw);
	D3DXVec3TransformNormal(&rmd,&rd,&iw);
	D3DXVec3Normalize(&rmd,&rmd);

	//test ray intersection on mesh
	D3DXIntersect(mesh->m_mesh,&rmo,&rmd,&hit,0,0,0,&dis,0,0);

	//return information
	*a_hit  = (hit)?true:false;
	*a_dis  = dis;
	*a_ori  = V3DF(rmo.x,rmo.y,rmo.z);
	*a_dir  = V3DF(rmd.x,rmd.y,rmd.z);

	return D3D_SUCCESS;
}